import React, { useEffect, useRef, useState } from 'react';
import { Divider, Form, FormInstance, Upload, Button, Image } from 'antd';
import ProForm, { ProFormRadio, ProFormText, ProFormCheckbox, ProFormDigit, ProFormDateTimeRangePicker, ModalForm, ProFormSelect } from '@ant-design/pro-form';
import { EditableProTable, ProColumns, ActionType } from '@ant-design/pro-table';
import { CloseCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { getGoodsSpecsList } from '@/services/stock-goods/api';
import { addShopGoods, updateShopGoods } from '@/services/shop/api';
import { getMallTag } from '@/services/mall/api';
import { MsgType, showMsg, isNull, getFileExtension, videoType, replaceImgHost, replaceRichTextImgHost, submitRichTextImgHost } from '@/utils/utils';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { imgHostUrl, miniPro } from '@/utils/constants';
import moment from 'moment'
import BraftEditor from 'braft-editor'
// 引入编辑器样式
import 'braft-editor/dist/index.css'
// @ts-ignore
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
// @ts-ignore
import Cookies from 'js-cookie';

let images: any[] = [];

interface MallGoodsInfoProps {
  goodsInfo: SHOPAPI.ShopGoods;
}

// 限时时间
let timeRange: string[] = []

const MallGoodsInfo: React.FC<MallGoodsInfoProps> = (props) => {
  const { goodsInfo } = props;
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [dataSource, setDataSource] = useState<STOCKGOODSAPI.GoodsSpecsItem[]>([]);
  const columns: ProColumns<STOCKGOODSAPI.GoodsSpecsItem>[] = [
    {
      title: '库存规格',
      dataIndex: 'specs_name',
      editable: false
    },
    {
      title: '规格描述',
      dataIndex: 'specs_desc',
      formItemProps: (myForm, record) => {
        return {
          style: {
            width: '100%'
          },
          rules: [
            {
              required: true,
              message: '此项是必填项',
              whitespace: true,
            },
          ]
        }
      }
    },
    {
      title: '计量单位',
      dataIndex: 'unit',
      editable: false
    },
    {
      title: '库存余量',
      editable: false,
      dataIndex: 'inventory',
      align: 'right',
      // renderText: (_, record) => {
      //   return Number(record.total_inventory || 0) - Number(record.wait_inventory || 0);
      // }
    },
    {
      title: '库存定价',
      dataIndex: 'selling_price',
      editable: false,
      align: 'right',
      valueType: 'money',
      fieldProps: {
        precision: 2
      },
    },
    {
      title: '商城定价',
      dataIndex: 'shop_selling_price',
      valueType: 'money',
      align: 'right',
      fieldProps: {
        precision: 2
      },
      formItemProps: (myForm, record) => {
        return {
          style: {
            width: '100%'
          },
          rules: [
            {
              required: true,
              message: '此项是必填项'
            },
            {
              validator: (_, value) => {
                console.log('z折扣价validator', value);
                if (value <= 0) {
                  return Promise.reject(new Error('不能为0'));
                }
                return Promise.resolve();
              },
              message: '商城定价不能为0',
            },
          ]
        }
      }
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      render: (_, record) => {
        return [
          <a key="edit" onClick={() => {
            actionRef.current?.startEditable(record.specs_id as string);
          }}>编辑</a>,
          <a key="delete" onClick={() => {
            const deletes = Object.assign([], deleteSpecs);
            const spesc = dataSource.find(item => item.id === record.id);
            deletes.push(spesc);
            setDeleteSpecs(deletes);
            setDataSource(dataSource.filter(item => item.id !== record.id));
          }}>删除</a>
        ]
      }
    }
  ]

  // 商品标签
  const [tagList, setTagList] = useState<any[]>([]);

  const [checkedTag, setCheckedTag] = useState<any[]>([]);

  // 显示限购时间
  const [showRangeTime, setShowRangeTime] = useState<boolean>(false);
  // 图片列表
  const [imageList, setImageList] = useState<any[]>([]);
  // 富文本编辑器
  const [editorState, setEditorState] = useState<any>(BraftEditor.createEditorState(null))

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const [newRecord, setNewRecord] = useState({
    id: (Math.random() * 1000000).toFixed(0)
  });

  const [saveLoading, setSaveLoading] = useState<boolean>(false);

  // 规格数量
  const [spescNum, setSpescNum] = useState<number>(0);

  // 规格列表
  const [spescList, setSpescList] = useState<STOCKGOODSAPI.GoodsSpecsItem[]>([]);

  // 删除的规格
  const [deleteSpecs, setDeleteSpecs] = useState<STOCKGOODSAPI.GoodsSpecsItem[]>([]);
  // 添加规格
  const [addSpesc, setAddSpesc] = useState<boolean>(false);

  useEffect(() => {
    // 编辑
    if (!isNull(goodsInfo.shop_goods_id)) {
      const list = goodsInfo.specs_list.map(item => {
        return {
          id: item.specs_id,
          ...item
        }
      })
      setDataSource(list || []);
      setSpescNum(list?.length || 0);

      // 获取商品规格
      getGoodsSpecsList({
        current: 1,
        pageSize: 10000,
        goods_id: goodsInfo.goods_id,
        goods_dept_code: goodsInfo.dept_code,
      }).then((data: STOCKGOODSAPI.GoodsSpecsItemList) => {
        const list = data.record_list?.map(item => {
          return {
            id: item.specs_id,
            ...item
          }
        });

        // 规格数不相等
        if (goodsInfo.specs_list.length !== list?.length) {
          const tempList: any[] = [];
          goodsInfo.specs_list?.forEach(item => {
            list?.forEach(item2 => {
              if (item2.specs_id !== item.specs_id) {
                tempList.push(item2);
              }
            });
          });

          console.log(tempList)
          setDeleteSpecs(tempList);
        }
        setSpescList(list || []);
      })

      images = []
      setImageList(images)

      setImageList(goodsInfo.attach_list.map(item => {
        images.push({
          id: item.attach_id,
          url: replaceImgHost(item.attach_thumb_url)
        })

        return {
          id: item.attach_id,
          url: replaceImgHost(item.attach_thumb_url)
        }
      }));

      // 标签有限时标志的
      goodsInfo.tag_list.forEach(item => {
        if (item.is_time === 'Y') {
          setShowRangeTime(true)
          // @ts-ignore
          timeRange = [item.begin_time, item.end_time]
        }
      })
      setCheckedTag(goodsInfo.tag_list);

      formRef.current?.setFieldsValue({
        shop_goods_name: goodsInfo.shop_goods_name,
        goods_status: goodsInfo.goods_status,
        show_price: goodsInfo.show_price,
        goods_detail: goodsInfo.goods_detail,
        tag_list: goodsInfo.tag_list.map(item => item.tag_id),
        time_range: timeRange
      });
      goodsInfo.goods_detail = replaceRichTextImgHost(goodsInfo.goods_detail);
      setEditorState(BraftEditor.createEditorState(goodsInfo.goods_detail))
    } else if (!isNull(goodsInfo.goods_id)) {
      // 新增商品
      images = []
      setImageList(images)
      getGoodsSpecsList({
        current: 1,
        pageSize: 10000,
        goods_id: goodsInfo.goods_id,
        goods_dept_code: goodsInfo.dept_code || goodsInfo.create_dept_code,
      }).then((data: STOCKGOODSAPI.GoodsSpecsItemList) => {
        const list = data.record_list?.map(item => {
          return {
            id: item.specs_id,
            ...item,
            shop_selling_price: item.selling_price,
            specs_desc: item.specs_name
          }
        })
        setDataSource(list || []);
        setSpescNum(list?.length || 0);
        setSpescList(list || []);

        // 获取所有的规格价格
        const prices: number[] = data.record_list?.map(item => {
          return Number(item.selling_price || 0)
        }) as number[]
        formRef.current?.setFieldsValue({
          // 商城显示价格，取最低价
          show_price: isNull(prices) ? 0 : Math.min(...prices)
        });
      })
    }
  }, [goodsInfo]);

  useEffect(() => {
    getMallTag().then((data: MALLAPI.MallTag[]) => {
      setTagList(data);
    })
  }, []);

  // @ts-ignore
  const onUploadChange = ({ fileList }) => {
    fileList.forEach((f: any, idx: number) => {
      if (f.status === 'done') {
        fileList.splice(idx, 1, {
          id: f.response[0].file_web_url,
          url: replaceImgHost(miniPro + f.response[0].file_web_url)
        } as any);
      } else if (f.status === 'error') {
        showMsg('文件上传失败');
        fileList.splice(idx, 1);
      }
    });
    setImageList([...fileList]);
  };

  // 移除图片
  const onRemove = (index: number) => {
    imageList.splice(index, 1);
    setImageList([...imageList]);
  }

  // 重排
  const reOrder = (list: any[], startIndex: number, endIndex: number) => {
    const result = Array.from(list);
    const [removed] = result.splice(startIndex, 1);
    result.splice(endIndex, 0, removed);
    return result;
  };

  const onDragEnd = (result: any) => {
    // dropped outside the list
    if (!result.destination) {
      return;
    }
    const items = reOrder(
      imageList,
      result.source.index,
      result.destination.index
    );
    setImageList(items)
  }

  // console.log('imglist', imageList)

  return <div className="mall-info">
    <div className="header">
      <div className="title">2.商城商品信息</div>
    </div>

    <Divider />

    <div className="info-body">
      <div className="warning">
        <ExclamationCircleOutlined style={{ marginRight: 10 }} />
        编辑完成后，请点击页面下方 <strong>保存</strong> 按钮保存结果。
      </div>
      <ProForm
        formRef={formRef}
        className="shop-goods-pro-form"
        scrollToFirstError={true}
        submitter={{
          // 完全自定义整个区域
          render: (props, doms) => {
            return <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
              <Button onClick={() => history.goBack()} style={{ marginRight: 10 }}>
                取消
              </Button>
              <Button loading={saveLoading} type='primary' onClick={() => formRef.current.submit?.()}>
                保存
              </Button>
            </div>;
          }
        }}
        onFinish={async (values) => {
          console.log(values)
          try {
            if (imageList.length === 0) {
              showMsg('请上传商品图片', MsgType.INFO);
              return;
            }

            const hasImage = imageList.some(item => {
              return `${item.url}`.endsWith('jpeg') || `${item.url}`.endsWith('png') || `${item.url}`.endsWith('jpg')
            })

            if (!hasImage) {
              showMsg('请上传至少一张图片', MsgType.INFO);
              return;
            }
            if (dataSource.length === 0) {
              showMsg('请至少添加一个规格', MsgType.INFO);
              return;
            }
            for (let i = 0; i < dataSource.length; i++) {
              if (!dataSource[i].shop_selling_price) {
                showMsg('请填写商品规格定价', MsgType.INFO);
                return;
              }
            }
            if (editableKeys.length > 0) {
              showMsg('您还有未保存的商品规格信息，请先保存！', MsgType.INFO);
              return
            }

            const postTagList: SHOPAPI.ShopGoodsTag[] = [];
            values?.tag_list?.forEach((tagId: string) => {
              tagList.forEach(item => {
                if (item.tag_id === tagId) {
                  if (item.is_time === 'Y') {
                    item.begin_time = moment(values.time_range[0]).format('YYYYMMDDHHmmss')
                    item.end_time = moment(values.time_range[1]).format('YYYYMMDDHHmmss')
                  }
                  postTagList.push(item);
                }
              })
            });

            const attach_list: any[] = [];
            imageList.forEach(item => {
              attach_list.push({
                id: item.id,
                attach_thumb_url: submitRichTextImgHost(item.url),
                attach_url: submitRichTextImgHost(item.url)
              })
            });

            delete values.time_range

            if (saveLoading) {
              return;
            }

            setSaveLoading(true);
            // 更新商品
            if (goodsInfo.shop_goods_id) {
              await updateShopGoods({
                ...goodsInfo,
                ...values,
                specs_list: dataSource,
                tag_list: postTagList,
                attach_list,
                goods_detail: submitRichTextImgHost(editorState.toHTML())
              } as SHOPAPI.ShopGoods);
            } else {
              // 添加商品
              await addShopGoods({
                ...goodsInfo,
                ...values,
                specs_list: dataSource,
                tag_list: postTagList,
                attach_list,
                goods_detail: submitRichTextImgHost(editorState.toHTML())
              } as SHOPAPI.ShopGoods);
              localStorage.removeItem('shop-goods-info');
            }
            images = []
            setImageList(images);
            setSaveLoading(false);

            history.push({
              pathname: '/shop/goods'
            });
          } catch (error) {
            console.log(error);
            setSaveLoading(false);
            showMsg(error?.data?.errmsg);
          }
        }}
        layout="horizontal">
        <ProForm.Group>
          <ProFormText
            name="shop_goods_name"
            width="md"
            rules={
              [
                {
                  required: true
                }
              ]
            }
            label="商城商品名称" />

          <ProFormRadio.Group
            label="商品状态"
            width="md"
            initialValue={goodsInfo.goods_status || 'O'}
            rules={
              [
                {
                  required: true
                }
              ]
            }
            name="goods_status"
            options={[
              {
                label: '上架',
                value: 'O'
              },
              {
                label: '下架',
                value: 'D'
              }
            ]} />
        </ProForm.Group>

        <ProForm.Group>
          <ProFormCheckbox.Group
            label="商品标签"
            name="tag_list"
            fieldProps={{
              onChange: (checkedValue) => {
                setCheckedTag(checkedValue);
                let checkFlag = false;
                const timeRangeList = tagList.filter(item => item.is_time === 'Y');

                checkedValue.forEach(value => {
                  timeRangeList.forEach(item => {
                    if (item.tag_id === value) {
                      checkFlag = true
                    }
                  })
                })

                if (checkedValue.length === 0) {
                  checkFlag = false
                }
                setShowRangeTime(checkFlag);
              }
            }}
            options={tagList.map(item => {
              return {
                label: item.tag_name,
                value: item.tag_id
              }
            })} />

          {
            showRangeTime && <ProFormDateTimeRangePicker
              name="time_range"
              rules={
                [
                  {
                    required: showRangeTime
                  }
                ]
              }
              label="限时抢购时间"
              fieldProps={{
                showTime: { defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')] },
              }}
            />
          }
        </ProForm.Group>

        <ProForm.Group>
          <ProFormDigit
            width="md"
            rules={
              [
                {
                  required: true
                }
              ]
            }
            name="show_price"
            label="展示价格"
            fieldProps={{
              precision: 2,
            }}
          />
          <Form.Item style={{ marginLeft: -100 }} colon={false} label="元" />
        </ProForm.Group>

        <ProForm.Group style={{ marginBottom: 10, fontSize: 12 }}>
          <div className="goods-picture">
            <div className="label">商品图片(视频)：</div>
            <span>单个商品允许包含至多5张图片及1个视频，视频时长不超过30s，如需调整展示顺序，请拖动图片位置。</span>
          </div>
        </ProForm.Group>

        <ProForm.Group style={{ marginBottom: 24 }}>
          <div className="upload-wrap">
            <DragDropContext onDragEnd={onDragEnd}>
              <Droppable droppableId="droppable" direction="horizontal">
                {(provided: any) => (
                  <div className="img-wrap" ref={provided.innerRef} {...provided.droppableProps}>
                    {imageList.map((item, index) => {
                      if (item.status === 'uploading') {
                        return <div className='ant-upload ant-upload-select-picture-card'><span className='ant-upload'><LoadingOutlined /></span></div>;
                      }
                      return videoType.includes(getFileExtension(item.url)) ? <div style={{ position: 'relative', marginRight: 8 }}>
                        <Draggable key={item.id} draggableId={item.url} index={index}>
                          {(provided: any) => (
                            <div ref={provided.innerRef}  {...provided.draggableProps} {...provided.dragHandleProps}>
                              <CloseCircleOutlined onClick={() => {
                                console.log(index);
                                onRemove(index);
                              }} className="icon-delete" />
                              <video
                                className="video"
                                controls
                                src={item.url} />
                            </div>
                          )}
                        </Draggable>
                      </div> :
                        <div style={{ position: 'relative', marginRight: 8 }}>
                          <Draggable key={item.id} draggableId={item.url} index={index}>
                            {(provided: any) => (
                              <div className="img" ref={provided.innerRef}  {...provided.draggableProps} {...provided.dragHandleProps} >
                                <CloseCircleOutlined onClick={() => {
                                  onRemove(index);
                                }} className="icon-delete" />
                                <Image width={102} height={102} src={item.url} />
                              </div>
                            )}
                          </Draggable>
                        </div>
                    })
                    }
                  </div>
                )}
              </Droppable>
            </DragDropContext>

            <Upload
              fileList={imageList}
              maxCount={6}
              multiple
              name="file"
              listType="picture-card"
              showUploadList={false}
              headers={{
                'Oper-Token': localStorage.getItem('Oper-Token')
              }}
              onChange={onUploadChange}
              beforeUpload={(file, fileList) => {
                let videoNum = 0;
                imageList.forEach(f => {
                  if (videoType.includes(getFileExtension(f.url)))
                    videoNum++;
                });
                if (imageList.length - videoNum >= 5) {
                  showMsg('最多可上传5张图片，1个视频');
                  return false;
                }
              }}
              action="/api/common/file/batch/upload">
              {imageList.length < 6 ? <PlusOutlined /> : ''}
            </Upload>
          </div>
        </ProForm.Group>

        <div style={{ fontSize: 12 }}>商品规格:</div>

        <ProForm.Group>
          <EditableProTable<STOCKGOODSAPI.GoodsSpecsItem>
            className="specs-table"
            actionRef={actionRef}
            rowKey="id"
            value={dataSource}
            onChange={setDataSource}
            recordCreatorProps={false}
            columns={columns}
            editable={{
              type: 'single',
              editableKeys,
              onChange: setEditableRowKeys
            }}
            bordered />

          <div className="ant-btn-dashed" style={{
            display: (goodsInfo.shop_goods_id ? dataSource.length !== spescList.length : spescNum !== dataSource.length) ? 'flex' : 'none',
            alignItems: 'center',
            justifyContent: 'center',
            width: window.innerWidth - 195 - 55,
            borderWidth: 1,
            fontSize: 12,
            cursor: 'pointer'
          }} onClick={() => {
            setAddSpesc(true);
          }}>
            <PlusOutlined style={{ marginRight: 10 }} />
            添加规格
          </div>
        </ProForm.Group>

        <div style={{ marginTop: 10, marginBottom: 10, fontSize: 12 }}>商品详情:</div>
        <ProForm.Group style={{ marginBottom: 15 }}>
          <BraftEditor
            onChange={setEditorState}
            excludeControls={[
              'remove-styles',
              'code',
              'emoji'
            ]}
            media={{
              uploadFn: (param) => {
                const serverURL = '/api/common/image/batch/upload-compress'
                const xhr = new XMLHttpRequest
                const fd = new FormData()

                const successFn = (response: any) => {
                  // 假设服务端直接返回文件上传后的地址
                  // 上传成功后调用param.success并传入上传后的文件地址
                  const fileList = JSON.parse(xhr.responseText)

                  // @ts-ignore
                  param.success({
                    url: replaceImgHost(miniPro + fileList[0].file_web_url)
                  })
                }

                const progressFn = (event: any) => {
                  // 上传进度发生变化时调用param.progress
                  param.progress(event.loaded / event.total * 100)
                }

                const errorFn = (response: any) => {
                  // 上传发生错误时调用param.error
                  param.error({
                    msg: '文件上传失败'
                  })
                }

                xhr.upload.addEventListener("progress", progressFn, false)
                xhr.addEventListener("load", successFn, false)
                xhr.addEventListener("error", errorFn, false)
                xhr.addEventListener("abort", errorFn, false)
                fd.append('file', param.file)
                xhr.open('POST', serverURL, true)
                xhr.setRequestHeader('Oper-Token', localStorage.getItem('Oper-Token'))
                xhr.send(fd)
              }
            }}
            value={editorState} />
        </ProForm.Group>
      </ProForm>
    </div>

    {
      addSpesc && <ModalForm
        title="添加规格"
        width="25%"
        visible
        modalProps={{
          maskClosable: false
        }}
        layout="horizontal"
        onVisibleChange={setAddSpesc}
        onFinish={async (value) => {
          const deleteSpecsList = deleteSpecs.concat([]);
          const index = deleteSpecsList.findIndex(item => item.specs_id === value.spesc_id);
          const specs = deleteSpecsList.find(item => item.specs_id === value.spesc_id);
          if (index > -1) {
            deleteSpecsList.splice(index, 1);
            setDeleteSpecs(deleteSpecsList);
          }
          const list = dataSource.concat([]);
          list.push(specs);
          setDataSource(list);
          setAddSpesc(false);
        }}
        submitter={{
          searchConfig: {
            resetText: '关闭',
            submitText: '保存'
          }
        }}>

        <ProForm.Group>
          <ProFormSelect
            rules={[
              {
                required: true
              }
            ]}
            width="md"
            options={deleteSpecs.map(item => {
              return {
                label: `${item.specs_name}`,
                value: item.specs_id as string
              }
            })}
            placeholder="请选择规格"
            name="spesc_id"
          />
        </ProForm.Group>
      </ModalForm>
    }
  </div>
}
export default MallGoodsInfo;
